import React from 'react'
import { Form, Input, Button, Toast } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import api from '../../axios/api' // 使用封装的axios实例
import { store } from '../../store'

function Login() {
  const navigate = useNavigate()

  const phoneReg = /^1[3-9]\d{9}$/
  const passwordReg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{6,20}$/

  const onFinish = async (value) => {
    try {
      const res = await api.post('/api/login', value)
      console.log(res);

      if (res.data.code === 200) {
        localStorage.setItem('token', res.data.data.token)
        localStorage.setItem('avatar', res.data.data.userInfo.avatar)
        localStorage.setItem('nickname', res.data.data.userInfo.nickname)
        store.dispatch({
          type: 'user/setUserInfo',
          payload: res.data.userInfo
        })

        navigate('/my')
      }
    } catch (error) {
      Toast.show({
        content: error.response?.data?.message || '登录失败，请重试',
        type: 'fail'
      })
    }
  }

  return (
    <div style={{ padding: '20px' }}>
      <Form
        layout='horizontal'
        onFinish={onFinish}
        footer={
          <Button block type='submit' color='primary' size='large' style={{ marginTop: '20px' }}>
            登录
          </Button>
        }
      >
        <Form.Item
          name='username'
          label='手机号'
          rules={[
            { required: true, message: '手机号不能为空' },
            { pattern: phoneReg, message: '请输入正确的手机号格式' }
          ]}
        >
          <Input placeholder='请输入手机号' />
        </Form.Item>
        <Form.Item
          name='password'
          label='密码'
          rules={[
            { required: true, message: '密码不能为空' },
            { pattern: passwordReg, message: '密码需6-20位，包含大小写字母、数字和特殊字符' }
          ]}
        >
          <Input type='password' placeholder='请输入密码' />
        </Form.Item>
      </Form>
    </div>
  )
}

export default Login